package com.toolbox.dal.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.toolbox.bo.AccountBO;
import com.toolbox.dal.mapper.InfraUserRoleMapper;
import com.toolbox.dal.model.InfraUserRoleDO;
import com.toolbox.dal.repository.InfraUserRoleDORepository;
import com.toolbox.req.InfraUserRoleReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author Mango
 * @since 2023-12-01
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class InfraUserRoleDORepositoryImpl extends ServiceImpl<InfraUserRoleMapper, InfraUserRoleDO> implements InfraUserRoleDORepository {

    @Autowired
    private InfraUserRoleMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void removeByRoleId(Long roleId) {
        mapper.delete(new QueryWrapper<InfraUserRoleDO>().lambda().eq(InfraUserRoleDO::getRoleId, roleId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void removeByUserId(Long userId) {
        mapper.delete(new QueryWrapper<InfraUserRoleDO>().lambda().eq(InfraUserRoleDO::getUserId, userId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<Long> createUserRole(InfraUserRoleReq req, AccountBO bo) {
        removeByUserId(req.getUserId());

        List<InfraUserRoleDO> list = Lists.newArrayList();

        for (Long roleId : req.getRoleIds()) {
            InfraUserRoleDO entityUserRole = new InfraUserRoleDO();

            entityUserRole.setRoleId(roleId);
            entityUserRole.setUserId(req.getUserId());

            entityUserRole.setCreatorId(bo.getUserId());
            entityUserRole.setCreatorName(bo.getNickname());

            entityUserRole.setModifierId(bo.getUserId());
            entityUserRole.setModifierName(bo.getNickname());

            list.add(entityUserRole);
        }

        // 批量插入
        saveBatch(list, list.size());

        return list.stream().map(InfraUserRoleDO::getId).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void removeById(Long id) {
        mapper.deleteById(id);
    }

}
